<template>
  <div class="current-occupancy">
    <Card title="当前占用记录" :bordered="false">
      <div class="occupancy-header">
        <Row :gutter="16">
          <Col :span="6">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="搜索资源名称、客户姓名"
              allow-clear
              @change="handleSearch"
            />
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.resourceType"
              placeholder="资源类型"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="PHYSICAL">物理资源</SelectOption>
              <SelectOption value="DIGITAL">数字资源</SelectOption>
              <SelectOption value="SERVICE">服务资源</SelectOption>
            </Select>
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.status"
              placeholder="占用状态"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="OCCUPIED">占用中</SelectOption>
              <SelectOption value="RESERVED">已预订</SelectOption>
              <SelectOption value="COMPLETED">已完成</SelectOption>
              <SelectOption value="CANCELLED">已取消</SelectOption>
            </Select>
          </Col>
          <Col :span="10">
            <Space>
              <Button type="primary" @click="handleSearch">搜索</Button>
              <Button @click="handleReset">重置</Button>
              <Button type="primary" @click="openOccupancyForm('create')">
                新增占用
              </Button>
              <Button @click="exportOccupancy">导出</Button>
            </Space>
          </Col>
        </Row>
      </div>

      <div class="occupancy-overview">
        <Row :gutter="16">
          <Col :span="6">
            <Statistic
              title="总占用数"
              :value="overview.total"
              :value-style="{ color: '#1890ff' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="占用中"
              :value="overview.occupied"
              :value-style="{ color: '#52c41a' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="已预订"
              :value="overview.reserved"
              :value-style="{ color: '#faad14' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="已完成"
              :value="overview.completed"
              :value-style="{ color: '#722ed1' }"
            />
          </Col>
        </Row>
      </div>

      <div class="occupancy-content">
        <Table
          :columns="columns"
          :data-source="occupancyList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'resourceType'">
              <Tag :color="getResourceTypeColor(record.resourceType)">
                {{ getResourceTypeText(record.resourceType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'amount'">
              <span class="amount">¥{{ record.amount.toFixed(2) }}</span>
            </template>
            <template v-else-if="column.key === 'action'">
              <Space>
                <Button type="link" size="small" @click="viewOccupancy(record)">
                  查看
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="openOccupancyForm('edit', record)"
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="completeOccupancy(record)"
                >
                  完成
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="cancelOccupancy(record)"
                >
                  取消
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </div>
    </Card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Statistic,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const occupancyList = ref<any[]>([]);
const total = ref(0);

const searchForm = reactive({
  keyword: '',
  resourceType: '',
  status: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const overview = reactive({
  total: 0,
  occupied: 0,
  reserved: 0,
  completed: 0,
});

const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 150,
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 120,
  },
  {
    title: '资源类型',
    dataIndex: 'resourceType',
    key: 'resourceType',
    width: 120,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 150,
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: 150,
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 模拟数据
const mockOccupancy = [
  {
    id: '1',
    resourceName: '豪华套房',
    customerName: '张三',
    resourceType: 'PHYSICAL',
    startTime: '2024-01-15 14:00:00',
    endTime: '2024-01-15 16:00:00',
    amount: 800.0,
    status: 'OCCUPIED',
  },
  {
    id: '2',
    resourceName: '温泉池',
    customerName: '李四',
    resourceType: 'PHYSICAL',
    startTime: '2024-01-15 15:00:00',
    endTime: '2024-01-15 17:00:00',
    amount: 300.0,
    status: 'OCCUPIED',
  },
  {
    id: '3',
    resourceName: 'VIP包间',
    customerName: '王五',
    resourceType: 'PHYSICAL',
    startTime: '2024-01-15 18:00:00',
    endTime: '2024-01-15 20:00:00',
    amount: 1200.0,
    status: 'RESERVED',
  },
  {
    id: '4',
    resourceName: '数字会议室',
    customerName: '赵六',
    resourceType: 'DIGITAL',
    startTime: '2024-01-15 09:00:00',
    endTime: '2024-01-15 11:00:00',
    amount: 500.0,
    status: 'COMPLETED',
  },
  {
    id: '5',
    resourceName: '按摩服务',
    customerName: '钱七',
    resourceType: 'SERVICE',
    startTime: '2024-01-15 16:00:00',
    endTime: '2024-01-15 17:00:00',
    amount: 200.0,
    status: 'OCCUPIED',
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));

    let filteredData = mockOccupancy;

    if (searchForm.keyword) {
      filteredData = filteredData.filter(
        (item) =>
          item.resourceName.includes(searchForm.keyword) ||
          item.customerName.includes(searchForm.keyword),
      );
    }

    if (searchForm.resourceType) {
      filteredData = filteredData.filter(
        (item) => item.resourceType === searchForm.resourceType,
      );
    }

    if (searchForm.status) {
      filteredData = filteredData.filter(
        (item) => item.status === searchForm.status,
      );
    }

    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;

    occupancyList.value = filteredData.slice(start, end);
    total.value = filteredData.length;
    pagination.total = total.value;

    // 更新概览数据
    updateOverview(filteredData);
  } catch (error) {
    console.warn('加载占用数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 更新概览数据
const updateOverview = (data: any[]) => {
  overview.total = data.length;
  overview.occupied = data.filter((item) => item.status === 'OCCUPIED').length;
  overview.reserved = data.filter((item) => item.status === 'RESERVED').length;
  overview.completed = data.filter(
    (item) => item.status === 'COMPLETED',
  ).length;
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    resourceType: '',
    status: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 打开占用表单
const openOccupancyForm = (type: 'create' | 'edit', record?: any) => {
  message.info(`${type === 'create' ? '新增' : '编辑'}占用记录功能开发中...`);
};

// 查看占用
const viewOccupancy = (record: any) => {
  message.info(`查看占用记录"${record.resourceName}"功能开发中...`);
};

// 完成占用
const completeOccupancy = (record: any) => {
  Modal.confirm({
    title: '确认完成',
    content: `确定要完成占用记录"${record.resourceName}"吗？`,
    onOk: async () => {
      try {
        message.success('占用记录已完成');
        loadData();
      } catch (error) {
        console.warn('操作失败:', error);
        message.error('操作失败');
      }
    },
  });
};

// 取消占用
const cancelOccupancy = (record: any) => {
  Modal.confirm({
    title: '确认取消',
    content: `确定要取消占用记录"${record.resourceName}"吗？`,
    onOk: async () => {
      try {
        message.success('占用记录已取消');
        loadData();
      } catch (error) {
        console.warn('操作失败:', error);
        message.error('操作失败');
      }
    },
  });
};

// 导出占用记录
const exportOccupancy = () => {
  message.success('占用记录导出成功');
};

// 工具函数
const getResourceTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    PHYSICAL: 'blue',
    DIGITAL: 'green',
    SERVICE: 'orange',
  };
  return colors[type] || 'default';
};

const getResourceTypeText = (type: string) => {
  const texts: Record<string, string> = {
    PHYSICAL: '物理资源',
    DIGITAL: '数字资源',
    SERVICE: '服务资源',
  };
  return texts[type] || type;
};

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    OCCUPIED: 'green',
    RESERVED: 'orange',
    COMPLETED: 'purple',
    CANCELLED: 'red',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    OCCUPIED: '占用中',
    RESERVED: '已预订',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  };
  return texts[status] || status;
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.current-occupancy {
  padding: 20px;
}

.occupancy-header {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.occupancy-overview {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.occupancy-content {
  margin-bottom: 24px;
}

.amount {
  color: #1890ff;
  font-weight: bold;
}
</style>
